package cn.beemango.dwb.bluetoothheadset;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.KeyEvent;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

import cn.beemango.dwb.bluetoothheadset.services.PlayerService;
import cn.beemango.dwb.bluetoothheadset.utils.LogUtil;

public class MainActivity extends AppCompatActivity {
    TextToSpeech myTts;
    String toSpeak = "This is a sample text that should play with Android default TTS engine.";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this, PlayerService.class));

        myTts = new TextToSpeech(getApplicationContext(), status -> {
            if (status != TextToSpeech.ERROR) {
                myTts.setLanguage(Locale.US);
            }
        });

        // Stupid Android 8 "Oreo" hack to make media buttons work
        final MediaPlayer mMediaPlayer;
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silent_sound);
        mMediaPlayer.setOnCompletionListener(mediaPlayer -> mMediaPlayer.release());
        mMediaPlayer.start();

        myTts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        LogUtil.i("onKeyDown KeyEvent ----> " + event + " keyCode ----> " + keyCode);
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            LogUtil.i("按下了音量加键");
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            LogUtil.i("按下了音量减键");
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
            // 有线或者蓝牙耳机的暂停播放
            LogUtil.i("中间按钮，暂停或播放");
            return true;
        } else return super.onKeyDown(keyCode, event);
    }
}
